package ljz.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import ljz.client.Client;
import ljz.message.LoginRequestMessage;
import ljz.message.LoginResponseMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;


@Slf4j
public class ClientInboundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("客户端连接到服务器");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入账号");
        String username = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        LoginRequestMessage loginMessage = new LoginRequestMessage();
        loginMessage.setUsername(username);
        loginMessage.setPassword(password);
        ctx.writeAndFlush(loginMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof LoginResponseMessage){
            LoginResponseMessage message = (LoginResponseMessage) msg;
            if (!message.isSuccess()) {
                ctx.channel().close();
            }else{
                log.debug("{}",message.getReason());
            }
        }
    }
}
